﻿using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using PizzaMario.Domain.Concrete;

namespace PizzaMario.Domain.Abstract
{

    public abstract class AbstractBaseRepository<T> where T : class
    {
        protected readonly DbSet<T> DbSet;
        private Context _context;

        protected AbstractBaseRepository(IDatabaseFactory databaseFactory)
        {
            DatabaseFactory = databaseFactory;
            DbSet = Context.Set<T>();
        }

        protected IDatabaseFactory DatabaseFactory { get; private set; }

        protected Context Context
        {
            get { return _context ?? (_context = DatabaseFactory.Get()); }
        }

        #region IRepository<T,TU> Members

        public virtual IQueryable<T> All()
        {
            return DbSet;
        }

        public virtual void Add(T entity)
        {
            DbSet.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            DbSet.Remove(entity);
        }

        public void Refresh(T entity)
        {
            Context.Entry(entity).Reload();
        }

        public bool IsValid()
        {
            foreach (var error in Context.GetValidationErrors().SelectMany(validationResults => validationResults.ValidationErrors))
            {
                Debug.WriteLine("Entity Property: {0}, Error {1}", error.PropertyName, error.ErrorMessage);
            }

            return !Context.GetValidationErrors().Any();
        }

        public void SaveChanges()
        {
            Context.SaveChanges();
        }
        #endregion
    }
}
